import { app, BrowserView, globalShortcut } from 'electron'

import { is } from '@electron-toolkit/utils'
import { join } from 'path'
import BasicFrame, { CreateFrame } from './common'
import path from 'path'

export default class mainFrame extends BasicFrame implements CreateFrame {
  #view: BrowserView | null = null
  #isReady = false

  constructor() {
    super('', {
      fullscreen: false,
      maximizable: true,
      resizable: true,
      width: 1900,
      height: 1000,
      ...(process.platform === 'linux'
        ? {
            icon: path.join(__dirname, '../../build/icon.png')
          }
        : {})
    })
  }

  create() {
    this.frame.on('ready-to-show', () => {
      this.#isReady = true
      globalShortcut.register('Ctrl+R', () => {
        this.frame.reload()
      })
    })

    // 当主窗体关闭时，则清空所有存储
    this.frame.on('close', () => {
      this.frame.webContents.session.clearStorageData().then(() => {
        if (process.platform !== 'darwin') {
          app.quit()
        }
      })
    })

    // HMR for renderer base on electron-vite cli.
    // 根据 electron-vite cli 进行渲染器的 HMR。
    // 根据环境变量加载远程 URL 进行开发，或者加载本地 HTML 文件进行生产。
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      //打开浏览器调试
      this.frame.webContents.openDevTools()
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      this.frame.webContents.openDevTools()
      this.frame.loadFile(join(__dirname, '../renderer/index.html'))
    }

    return this
  }

  isReady() {
    return this.#isReady
  }

  addBrowserView(view: BrowserView) {
    this.#view = view
    this.frame.addBrowserView(view)
  }

  removeBrowserView() {
    this.#view && this.frame.removeBrowserView(this.#view)
  }
}
